package com.cmcc.driver.ui.main


import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.telephony.CellLocation.requestLocationUpdate
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.core.content.ContextCompat.getSystemService
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.amap.api.maps.model.LatLng
import com.cmcc.driver.R
import com.cmcc.driver.config.DriverPath
import com.cmcc.driver.data.DriverDataRepository
import com.cmcc.driver.data.entity.Order
import com.cmcc.driver.databinding.FragmentOrderReceiveBinding
import com.cmcc.driver.ui.dialog.AppAlertDialog
import com.cmcc.driver.ui.dialog.AppProgressDialog
import com.cmcc.driver.ui.main.adapter.OrderReceiveAdapter
import com.cmcc.driver.ui.main.viewmodel.OrderReceiveViewModel
import com.cmcc.driver.util.LocationUtil
import com.cmcc.shared.adapter.SpaceItemDecoration
import com.cmcc.shared.utils.DisplayUtil
import com.cmcc.shared.utils.SpHelper
import com.cmcc.shared.utils.clickWithTrigger
import com.google.android.gms.location.*
import java.util.*


/**
 * Author: jiangxin
 * Date: 2019/11/5
 * Description:
 */
class OrderReceiveFragment : Fragment(), OrderReceiveAdapter.OnReceiveListener {

    private var orderList: List<Order>? = null
    private lateinit var adapter: OrderReceiveAdapter


    private var viewModel: OrderReceiveViewModel? = null
    private lateinit var binding: FragmentOrderReceiveBinding

    private var timer: Timer? = null

    private var progressDialog: AppProgressDialog? = null


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentOrderReceiveBinding.inflate(inflater, container, false)
        binding.recyclerView.layoutManager = LinearLayoutManager(activity)
        binding.recyclerView.addItemDecoration(
            SpaceItemDecoration(
                DisplayUtil.dp2px(
                    context!!,
                    20f
                ).toInt()
            )
        )
        adapter = OrderReceiveAdapter()
        adapter.setOnReceiveListener(this)
        binding.recyclerView.adapter = adapter

        binding.swipeRefreshLayout.setOnRefreshListener {
            updateUI()
        }

        viewModel = ViewModelProviders.of(this).get(OrderReceiveViewModel::class.java)
        progressDialog = AppProgressDialog(context!!)

        binding.onOrder.clickWithTrigger {
            if (activity is DriverMainActivity)
                (activity as DriverMainActivity).currentPage(
                    R.id.order_progress
                )
        }

        viewModel?.orderList?.observe(this, Observer { list ->
            orderList = list
            adapter.submitList(list)
            adapter.notifyDataSetChanged()
            if(list.isEmpty()){
                binding.noOrderLayout.visibility = View.VISIBLE
            }else{
                binding.noOrderLayout.visibility = View.GONE
            }
        })

        viewModel?.orderDoingNetStatus?.observe(this, Observer {
            binding.swipeRefreshLayout.isRefreshing = it
        })


        viewModel?.carInfo?.observe(this, Observer { carInfo ->
            AppAlertDialog(context!!).setContent(
                getString(
                    R.string.car_number_dialog_message,
                    carInfo.idCard
                )
            ).setNavigation(getString(R.string.car_number_not_change), null)
                .setPositive(getString(R.string.car_number_change),
                    View.OnClickListener {
                        ARouter.getInstance().build(DriverPath.TAXI_INFORMATION).navigation()
                    }).show()
        })

        viewModel?.orderReceiving?.observe(this, Observer { orderReceiving ->
            progressDialog?.dismiss()
            val code = orderReceiving.code
            when(code){
                200->{
                    //                if (activity is DriverMainActivity)
//                    (activity as DriverMainActivity).currentPage(
//                        R.id.order_progress
//                    )
                    //拒单finish()有返回的
                    ARouter.getInstance().build(DriverPath.ORDER_IN_PROGRESS_DETAIL)
                        .withString("orderId", orderReceiving.data).navigation(activity, 101)
                    DriverDataRepository.getInstance().hasStatusChange().value = true
                }
                400->
                    Toast.makeText(
                        context!!,
                        orderReceiving.msg,
                        Toast.LENGTH_LONG
                    ).show()
                1001->
                    Toast.makeText(
                        context!!,
                        orderReceiving.msg,
                        Toast.LENGTH_LONG
                    ).show()
                1003 ->{
                    Toast.makeText(
                        context!!,
                        orderReceiving.msg,
                        Toast.LENGTH_LONG
                    ).show()
                }
                else->
                    AppAlertDialog(context!!).setContent(getString(R.string.driver_has_doing_order))
                        .setNavigation("", null, false)
                        .setPositive(getString(R.string.make_sure), View.OnClickListener {
                            if (activity is DriverMainActivity)
                                (activity as DriverMainActivity).currentPage(
                                    R.id.order_progress
                                )
                        })
                        .show()
            }
        })

        viewModel?.isorderDoing?.observe(this, Observer {
            binding.onOrder.visibility = if (!it) View.GONE else View.VISIBLE
            adapter.setHasOrderDoing(it)
            adapter.notifyDataSetChanged()

        })

        viewModel?.hasStatusChange()?.observe(this, Observer {
            if(it){
                updateUI()
            }
        })

        initLocation();
        requestLocationPermission()


        if(SpHelper.getParam(context!!,"Status","driver",true)){
            viewModel?.requestCarInfo()
            SpHelper.setParam(context!!,"Status","driver",false)
        }


        return binding.root
    }
    private lateinit var fusedLocationClient: FusedLocationProviderClient
    private lateinit var locationRequest: LocationRequest
    private lateinit var locationCallback: LocationCallback
    private fun initLocation() {
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this.activity!!)

        locationRequest = LocationRequest()
        locationRequest.interval = 5 * 1000L//请求时间间隔
        locationRequest.fastestInterval = 1500L//最快时间间隔
        locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY

        locationCallback = object : LocationCallback() {
            override fun onLocationResult(locationResult: LocationResult?) {
                if (locationResult == null) return
                handleLocation(locationResult.lastLocation)
            }
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 101) {
            if (!data?.getStringExtra("id").isNullOrBlank()) {
                val filterNot = orderList?.filterNot { order ->
                    id.equals(order.id)
                }
                adapter.submitList(filterNot)
                adapter.notifyDataSetChanged()
            }
        }
    }

    override fun onPause() {
        timer?.cancel()
        timer = null
        super.onPause()
    }

    companion object {
        const val NEARBY_ORDER_PERIOD = 15 * 1000L
    }

    override fun onReceiveClick(orderId: String,orderType:Int) {
        progressDialog?.show()
//        if(orderType == 1){
            viewModel?.receivingOrder(orderId)
//        }else{
//            viewModel?.actionOrder(orderId)
//        }
    }

    fun updateUI() {

        var latLng = LocationUtil.getInstance().getCurrentLoc()
        if (latLng != null) {
            viewModel?.nearbyOrder(latLng)
            viewModel?.queryOrderProgress()
        }

    }


    /**
     * 获取当前位置的回调方法
     */
    private fun handleLocation(currentLocation: Location) {
        Log.e("currentLocation",currentLocation.toString())
        val lat = currentLocation.latitude
        val lng = currentLocation.longitude
        if (lat != 0.0 && lng != 0.0) {
            val appointLoc = com.google.android.gms.maps.model.LatLng(lat, lng)
            LocationUtil.getInstance().setCurrentLoc(appointLoc)

            var latLng = LocationUtil.getInstance().getCurrentLoc()
            if (latLng != null) {
                viewModel?.nearbyOrder(latLng)
                viewModel?.queryOrderProgress()
            }



        }
    }

    /**
     * 动态请求定位权限
     */
    private fun requestLocationPermission() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            requestLocationService()
            return
        }
        if (ContextCompat.checkSelfPermission(
                this!!.activity!!,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED
        ) {
            requestLocationService()
        } else {
            requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 1)
        }
    }
    private fun stopLocationUpdate() {
        fusedLocationClient.removeLocationUpdates(locationCallback)
    }

    /**
     * 请求定位服务
     */
    private fun requestLocationService() {
        val locationManager = activity!!.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            requestLocationUpdate()
        }
    }


    override fun onDestroyView() {
        super.onDestroyView()
        stopLocationUpdate()
    }

    /**
     * 请求位置更新
     */
    private fun requestLocationUpdate() {
        fusedLocationClient.requestLocationUpdates(
            locationRequest,
            locationCallback,
            Looper.myLooper()
        )
    }

}